import { Router } from '@angular/router';
import { environment } from '@env/environment';
import { Component, OnInit, ViewChild, TemplateRef, ChangeDetectorRef } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { SocialService } from '@delon/auth';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { STData, STComponent, STColumn, STChange, STPage } from '@delon/abc';
import { NzMessageService, NzModalService, NzNotificationService, UploadFile } from 'ng-zorro-antd';
import { Observable, fromEvent, Observer } from 'rxjs';
import { DomSanitizer } from '@angular/platform-browser';
import { SFSchema } from '@delon/form/src/schema';

@Component({
  selector: 'app-goods',
  templateUrl: './goods.component.html',
  styleUrls: ['./goods.component.less']
})
export class GoodsComponent implements OnInit {

  @ViewChild('file', { static: false })
  file: any; // input
  data: any[] = []; // table 数据源
  url: string; // 新增、修改、删除 地址
  form: FormGroup; // 新增、修改表单数据
  loading = false; // 表单遮蔽层
  selectedRows: STData[] = []; //   checkbox选中的行
  @ViewChild('modalContent', { static: true })
  modalContent: TemplateRef<{}>;  // 新增、修改模板
  expandForm = false; // 查询框的收缩、展开
  query: any = {
    pageNo: 1, // 页码
    pageSize: 10, // 页数
    orderBy: '', // 排序
    condition: {} // 条件
  }; // 查询条件
  item = {}; // 选中的行 单条
  page: any = {
    total: 0, //  默认0
    range: [0, 10], // 范围
    pageParam: {
      front: false, // 是否前端控制分页
      showSize: true, // 是否显示分页器中改变页数
      showQuickJumper: true, // 是否显示分页器中快速跳转
      indexReset: false,
      total: '共有{{total}}条数据，当前{{range[0]}}-{{range[1]}}行',
    }  // STPage
  } // table 分页器

  specificationList = []; // 产品规格列表

  @ViewChild('st', { static: true })
  st: STComponent;
  columns: STColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    {
      title: '行号', type: 'no', width: '60px',
    },
    {
      title: '产品规格', index: 'text',
      sort: {
        compare: (a, b) => a.text.localeCompare(b.text)
      },
      filter: {
        type: 'keyword',
        fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
      }
    },
    {
      title: '商品名称', index: 'name',
      sort: {
        compare: (a, b) => a.name.localeCompare(b.name)
      },
      filter: {
        type: 'keyword',
        fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
      }
    },
    {
      title: '品牌', index: 'brand',
      sort: {
        compare: (a, b) => a.brand.localeCompare(b.brand)
      },
      filter: {
        type: 'keyword',
        fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
      }
    },
    {
      title: '是否上架', index: 'isShelves',
      sort: {
        compare: (a, b) => a.isShelves.localeCompare(b.isShelves)
      },
      filter: {
        type: 'keyword',
        fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
      }
    },
    {
      title: '最低价格', index: 'minPrice',
      sort: {
        compare: (a, b) => a.minPrice.localeCompare(b.minPrice)
      },
      filter: {
        type: 'keyword',
        fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
      }
    },
    {
      title: '厂家推荐零售价', index: 'retailPrice',
      sort: {
        compare: (a, b) => a.retailPrice.localeCompare(b.retailPrice)
      },
      filter: {
        type: 'keyword',
        fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
      }
    },
    // {
    //   title: '更新时间', index: 'updateDate', type: 'date',
    //   sort: {
    //     compare: (a, b) => a.serialNum.localeCompare(b.serialNum)
    //   },
    //   filter: {
    //     type: 'keyword',
    //     fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1,
    //   }
    // },
    {
      title: '操作',
      buttons: [
        {
          text: '商品详情',
          click: (item: any) => this.open(item),
        },
        {
          text: '添加商品型号',
          click: (item: any) => this.goToPage(item),
        },
        {
          text: '修改',
          click: (item: any) => this.update(item),
        },
        {
          text: '删除',
          click: (item: any) => this.deleteConfirm(item),
        }
      ],
    },
  ];

  // 嵌套子表
  childrenColumns: STColumn[] = [
    {
      title: '属性名称', index: 'name',
      sort: {
        compare: (a, b) => a.name.localeCompare(b.name)
      }
    },
    {
      title: '属性值', index: 'value',
      sort: {
        compare: (a, b) => a.value.localeCompare(b.value)
      }
    },
    {
      title: '排序号', index: 'serialNumber',
      sort: {
        compare: (a, b) => a.serialNumber.localeCompare(b.serialNumber)
      }
    },
    {
      title: '操作',
      buttons: [
        {
          text: '修改',
          click: (item: any) => this.updateChildRen(item),
        },
        {
          text: '删除',
          click: (item: any) => this.deleteConfirmChildRen(item),
        }
      ],
    },]

  pageParam: STPage = {
    front: false,
    show: false,
  }  // STPage 子表格分页配置
  formChildRen: FormGroup; // 新增、修改表单数据 
  @ViewChild('modalContentChildRen', { static: true })
  modalContentChildRen: TemplateRef<{}>;  // 新增、修改模板
  attributesIdList = []; // 商品属性列表
  visible = false;
  value: any;// 文本编辑


  // 相册图片参数
  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true
  };
  fileList = [
  ];
  previewImage: string | undefined = '';
  previewVisible = false;
  height: any = 0;

  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private cdr: ChangeDetectorRef,
    private fb: FormBuilder,
    private notification: NzNotificationService,
    private domsanitizer: DomSanitizer,
    private router: Router
  ) {
    const that = this;
    that.height = window.innerHeight;
    fromEvent(window, 'resize')
      .subscribe((event) => {
        that.height = window.innerHeight;

      });
  }

  ngOnInit() {
    // 表单初始化
    this.form = this.fb.group({
      goodsId: [null],
      specificationId: [null],
      name: [null, [Validators.required]],
      text: [null, [Validators.required]],
      isShelves: [null, [Validators.required]],
      brand: [null],
      minPrice: [null],
      retailPrice: [null],
      tempText: [null], // 临时值
    });

    this.formChildRen = this.fb.group({
      goodsId: [null],
      goodsAttributesId: [null],
      attributesId: [null],
      name: [null, [Validators.required]],
      value: [null, [Validators.required]],
      serialNumber: [null],
      tempText: [null], // 临时值
    });

    this.getData();
    this.getSpecification();
    this.getAttributes();
  }


  _change(value: string) {
  }

  open(data: any): void {
    this.item = data;
    this.visible = true;
    // tslint:disable-next-line:no-string-literal
    this.getPhotoDetail(data['goodsId']);
  }

  close(): void {
    this.visible = false;
  }

  /**
   * 前往其他页面
   */
  goToPage(data: any) {
    this.router.navigateByUrl("/zfy/goods/goods-type?id=" + data.goodsId);
  }

  /**
   * 获取产品规格
   */
  getSpecification() {
    const query = {
      pageNo: 1, // 页码
      pageSize: 50, // 页数
      orderBy: '', // 排序
      condition: { status: "启用" } // 条件
    }
    this.http.post("/zfy/ZfySpecification/zfyspecification/getByPage", query).subscribe(res => {
      if (res.code === 0) {
        this.specificationList = res.data.list;
      }
    })
  }

  /**
   * 获取商品属性
   */
  getAttributes() {
    const query = {
      pageNo: 1, // 页码
      pageSize: 50, // 页数
      orderBy: '', // 排序
      condition: {} // 条件
    }
    this.http.post("/zfy/Attributes/attributes/getByPage", query).subscribe(res => {
      if (res.code === 0) {
        this.attributesIdList = res.data.list;
      }
    })
  }

  /**
   * 获取列表数据
   */
  getData() {
    this.loading = true;
    this.http.post("/zfy/Goods/goods/getByPage", this.query).subscribe(res => {
      this.loading = false;
      if (res.code === 0) {
        this.changeData(res.data)
        return;
      }
      this.notification.error(res.message + "！！！错误！", ``);
    })
  }

  /**
   * 查询数据
   */
  serchData() {
    // 清空分页参数
    this.query.pageNo = 1;
    this.getData();
  }

  /**
   * 当获取到数据后对数据进行拆分保存
   * @param data 数据源
   */
  changeData(data: any) {
    // for (let i = 0, no = data.startRow; no < data.endRow; i++ , no++) {
    //   data.list[i]['no'] = no;
    // } 
    this.data = data.list;
    for (const it of this.data) {
      it.showExpand = true
    }
    this.selectedRows = [];
    this.page.total = data.total;
    this.page.range = [data.startRow, data.endRow];
    this.cdr.detectChanges();
  }

  /**
   * 新增（单条记录）
   * @param tpl 模板
   */
  add() {
    this.url = '/zfy/Goods/goods/save';
    this.form.reset();
    this.modalSrv.create({
      nzTitle: '新建商品',
      nzContent: this.modalContent,
      nzOnOk: () => new Promise((resolve) => {
        this.addItem(this.url, this.form.value).subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message)
            this.getData();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   * 修改（单条记录） 
   * @param item 行数据
   */
  update(item: any) {
    this.url = '/zfy/Goods/goods/update';
    this.form.reset();
    for (const key of Object.keys(this.form.value)) {
      this.form.controls[key].setValue(item[key]);
    }

    // 拼接
    // tslint:disable-next-line:no-string-literal
    const tempText = item['text'] + ',' + item['specificationId'];
    // tslint:disable-next-line:no-string-literal
    this.form.controls['tempText'].setValue(tempText);
    this.modalSrv.create({
      nzTitle: '修改商品',
      nzContent: this.modalContent,
      nzOnOk: () => new Promise((resolve) => {
        this.updateItem(this.url, this.form.value).subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message)
            this.getData();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   * 新增保存记录（单条） 
   */
  addItem(url: string, formValue: any): Observable<any> {
    return new Observable<any>(ob => {
      this.http.post(url, formValue).subscribe(res => {
        ob.next(res);
      })
    })
  }

  /**
   * 修改保存记录（单条） 
   */
  updateItem(url: string, formValue: any): Observable<any> {
    return new Observable<any>(ob => {
      this.http.put(url, formValue).subscribe(res => {
        ob.next(res);
      })
    })
  }

  /**
   * 删除提示框
   * @param item 行数据
   */
  deleteConfirm(item: any) {
    this.url = '/zfy/Goods/goods/delete?id=' + item.goodsId;
    this.modalSrv.confirm({
      nzTitle: '提示',
      nzContent: '确认删除（单条）记录？',
      nzOnOk: () => new Promise(resolve => {
        this.deleteItem(this.url).subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message)
            this.getData();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   * 删除记录（单条）
   * @param item 行数据
   */
  deleteItem(url: string): Observable<any> {
    return new Observable(ob => {
      this.http.delete(url).subscribe(res => {
        ob.next(res);
      })
    })
  }

  /**
   * 批量删除提示框
   */
  batchDeleteConfirm() {
    if (this.selectedRows.length <= 0) {
      this.msg.error('未选中数据');
      return;
    }

    const array = new Array();
    for (const item of this.selectedRows) {
      array.push(item.goodsId)
    }
    this.url = '/zfy/Goods/goods/batchDelete?ids=' + array.join(',');
    this.modalSrv.confirm({
      nzTitle: '提示',
      nzContent: '确认删除（选中行）记录？',
      nzOnOk: () => new Promise(resolve => {
        this.batchDeleteItems().subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message + '共删除' + res.data + '条记录');
            this.getData();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   *  批量删除
   */
  batchDeleteItems(): Observable<any> {
    return new Observable(ob => {
      this.http.delete(this.url).subscribe(res => {
        ob.next(res);
      })
    })
  }

  /**
   * tbale 选中行、分页改变 
   * @param e 数据
   */
  stChange(e: STChange) {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox;
        break;
      case 'pi':
        this.query.pageNo = e.pi;
        this.query.pageSize = e.ps;
        this.getData();
        break;
      case 'ps':
        this.query.pageNo = e.pi;
        this.query.pageSize = e.ps;
        this.getData();
        break;
      case 'expand':
        if (e.expand.expand) {
          this.item = e.expand;
          this.getPhotoList(e.expand);
          this.getDataChildRen();
        }
        break;
    }
  }


  reset() {
    // wait form reset updated finished
    setTimeout(() => this.getData());
  }

  /**
   * 下拉改变是回调
   * @param e value值
   */
  provinceChange(e: any) {
    const data = e.split(',');
    const that = this;
    // tslint:disable-next-line:no-string-literal
    that.form.controls['specificationId'].setValue(data[1]);
    // tslint:disable-next-line:no-string-literal
    that.form.controls['text'].setValue(data[0]);
  }

  /**
   * 文件上传
   */
  uploadFile(data: any) {
    this.item = data;
    this.file.nativeElement.click()
  }

  /**
   * 文件选择完毕
   */
  fileSelect(e: any) {
    const formData = new FormData();
    const list = e.target.files;
    for (const item of list) {
      const name = item.name;
      if (name === '' || name === null || name === undefined) {
        this.modalSrv.error({
          nzTitle: '提示',
          nzContent: '请上传照片',
        });
        return;
      }
      const temp = name.split('.');
      const type: string = temp[temp.length - 1].toUpperCase();
      if (!(type === 'JPG' || type === 'JPEG' || type === 'PNG')) {
        this.modalSrv.error({
          nzTitle: '提示',
          nzContent: '请上传照片JPG,PNG格式的照片',
        });
        return;
      }
      formData.append(name, item);
    }
    // tslint:disable-next-line:no-string-literal
    formData.append('goodsId', this.item['goodsId']);

    this.http.post('/zfy/GoodsPhoto/goodsphoto/uploadFile', formData, { headers: { enctype: 'multipart/form-data' } }).subscribe(res => {
      if (res.code === 0) {
        if (res.data <= 0) {
          this.msg.error("图片上传失败");
        } else {
          this.msg.success("图片上传成功");
          this.getPhotoList(this.item);
        }
      }
    })
  }

  /**
   * 文件上传
   * @param e shuju 
   */
  beforeUpload = (file: File) => {
    return new Observable((observer: Observer<boolean>) => {
      const formData = new FormData();
      const name = file.name;
      if (name === '' || name === null || name === undefined) {
        this.modalSrv.error({
          nzTitle: '提示',
          nzContent: '请上传照片',
        });
        observer.complete();
        return;
      }
      const temp = name.split('.');
      const type: string = temp[temp.length - 1].toUpperCase();
      if (!(type === 'JPG' || type === 'JPEG' || type === 'PNG')) {
        this.modalSrv.error({
          nzTitle: '提示',
          nzContent: '请上传照片JPG,PNG格式的照片',
        });
        observer.complete();
        return;
      }
      formData.append(name, file);
      // tslint:disable-next-line:no-string-literal
      formData.append('goodsId', this.item['goodsId']);
      this.http.post('/zfy/GoodsDetailPhoto/goodsdetailphoto/uploadFile', formData, { headers: { enctype: 'multipart/form-data' } }).subscribe(res => {
        if (res.code === 0) {
          if (res.data <= 0) {
            this.msg.error("图片上传失败");
          } else {
            this.msg.success("图片上传成功");
            this.getPhotoList(this.item);
          }
        }
        observer.next(true);
        observer.complete();
        return;
      })
      return;
    });
  };


  /**
   * 每一行里面的图片获取
   * @param data 行数据
   */
  getPhotoList(data: object) {
    const query: any = {
      pageNo: 1, // 页码
      pageSize: 30, // 页数
      orderBy: '', // 排序
      // tslint:disable-next-line:no-string-literal
      condition: { 'goodsId': data['goodsId'] } // 条件
    }; // 查询条件
    this.http.post('/zfy/GoodsPhoto/goodsphoto/getByPage', query).subscribe(res => {
      if (res.code === 0) {
        // tslint:disable-next-line:no-string-literal
        data['fileList'] = res.data.list;
      }
    })
  }

  /**
   * 图片地址安全回显
   */
  showIcon(url: any) {
    if (url === '' || url === null || url === undefined) return '';
    else return this.domsanitizer.bypassSecurityTrustResourceUrl(url);
  }

  /**
   * 设置封面图
   * @param data 数据
   */
  updatePhoto(data: any) {
    this.http.put('/zfy/GoodsPhoto/goodsphoto/update', data).subscribe(res => {
      if (res.code === 0) {
        this.msg.success('设置成功');
        this.getPhotoList(this.item);
      }
    });
  }

  /**
   * 删除图片
   */
  deletePhoto(data: any) {
    this.http.delete('/zfy/GoodsPhoto/goodsphoto/deleteFile?id=' + data.goodsPhotoId).subscribe(res => {
      if (res.code === 0) {
        this.msg.success('删除成功');
        this.getPhotoList(this.item);
      }
    });
  }


  /**
   * 获取子表列表数据
   */
  getDataChildRen() {
    const query = {
      pageNo: 1, // 页码
      pageSize: 50, // 页数
      orderBy: '', // 排序
      // tslint:disable-next-line:no-string-literal
      condition: { 'goodsId': this.item['goodsId'] } // 条件
    }
    this.http.post("/zfy/GoodsAttributes/goodsattributes/getByPage", query).subscribe(res => {
      if (res.code === 0) {
        // tslint:disable-next-line:no-string-literal
        this.item['dataChildRen'] = res.data.list;
        return;
      }
      this.notification.error(res.message + "！！！错误！", ``);
    })
  }


  /**
   * 新增（单条记录）
   * @param tpl 模板
   */
  addChildRen() {
    this.url = '/zfy/GoodsAttributes/goodsattributes/save';
    this.formChildRen.reset();
    // tslint:disable-next-line:no-string-literal
    this.formChildRen.controls['goodsId'].setValue(this.item['goodsId']);
    this.modalSrv.create({
      nzTitle: '新建商品属性',
      nzContent: this.modalContentChildRen,
      nzOnOk: () => new Promise((resolve) => {
        this.addItem(this.url, this.formChildRen.value).subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message)
            this.getDataChildRen();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   * 修改（单条记录） 
   * @param item 行数据
   */
  updateChildRen(item: any) {
    this.url = '/zfy/GoodsAttributes/goodsattributes/update';
    this.formChildRen.reset();
    for (const key of Object.keys(this.formChildRen.value)) {
      this.formChildRen.controls[key].setValue(item[key]);
    }

    // 拼接
    // tslint:disable-next-line:no-string-literal
    const tempText = item['name'] + ',' + item['attributesId'];
    // tslint:disable-next-line:no-string-literal
    this.formChildRen.controls['tempText'].setValue(tempText);
    this.modalSrv.create({
      nzTitle: '修改商品属性',
      nzContent: this.modalContentChildRen,
      nzOnOk: () => new Promise((resolve) => {
        this.updateItem(this.url, this.formChildRen.value).subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message)
            this.getDataChildRen();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }

  /**
   * 删除提示框
   * @param item 行数据
   */
  deleteConfirmChildRen(item: any) {
    this.url = '/zfy/GoodsAttributes/goodsattributes/delete?id=' + item.goodsAttributesId;
    this.modalSrv.confirm({
      nzTitle: '提示',
      nzContent: '确认删除（单条）记录？',
      nzOnOk: () => new Promise(resolve => {
        this.deleteItem(this.url).subscribe(res => {
          if (res.code === 0) {
            this.msg.success(res.message)
            this.getDataChildRen();
          } else {
            this.msg.error(res.message);
          }
          resolve();
        })
      })
    })
  }


  /**
   * 下拉改变是回调
   * @param e value值
   */
  provinceChangeChildRen(e: any) {
    const data = e.split(',');
    const that = this;
    // tslint:disable-next-line:no-string-literal
    that.formChildRen.controls['attributesId'].setValue(data[1]);
    // tslint:disable-next-line:no-string-literal
    that.formChildRen.controls['name'].setValue(data[0]);
  }

  /**
   * 获取商品详情照片
   */
  getPhotoDetail(goodsId: string) {
    const query = {
      pageNo: 1, // 页码
      pageSize: 50, // 页数
      orderBy: '', // 排序
      condition: { 'goodsId': goodsId } // 条件
    }
    this.http.post("/zfy/GoodsDetailPhoto/goodsdetailphoto/getByPage", query).subscribe(res => {
      if (res.code === 0) {
        res.data.list.forEach(element => {
          element.uid = element.goodsDetailPhotoId;
          element.name = element.fileName;
          element.status = 'done';
          // element.url = this.domsanitizer.bypassSecurityTrustResourceUrl(element.filePath);
          // element.url = "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png";
          element.url = element.filePath;
        });
        this.fileList = res.data.list;
      }
    })
  }

  remove = (file: UploadFile) => {
    const goodsId = file.goodsId;
    const goodsDetailPhotoId = file.goodsDetailPhotoId;
    this.http.delete('/zfy/GoodsDetailPhoto/goodsdetailphoto/deleteFile?id=' + goodsDetailPhotoId).subscribe(res => {
      if (res.code === 0) {
        this.getPhotoDetail(goodsId);
      }
    });
  }
}
